package cn.geminis.everydata.service.controller;

import cn.geminis.core.data.query.QueryParameters;
import cn.geminis.core.util.JsonUtils;
import cn.geminis.data.jpa.GeminiRepository;
import cn.geminis.everydata.service.entity.Category;
import cn.geminis.everydata.service.entity.Form;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author puddi
 */
@RestController
@RequestMapping("/forms")
@AllArgsConstructor
public class FormController {

    private final GeminiRepository repository;

    @PostMapping
    public Page<Form> findPage(@RequestBody final QueryParameters queryParameters) {
        return this.repository.findPage(Form.class, queryParameters);
    }

    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public void save(@RequestBody Form form) {
        this.repository.save(form);
    }

    @DeleteMapping
    public void delete(@RequestBody List<String> ids) {
        ids.forEach(id -> this.repository.deleteById(Form.class, id));
    }

    @PutMapping("/{id}/move/{category}")
    public void move(@PathVariable String id, @PathVariable String category) {
        var form = this.repository
                .findById(Form.class, id)
                .get();
        var categoryObj = new Category();
        categoryObj.setId(category);
        form.setCategory(categoryObj);
        this.repository.save(form);
    }

    @GetMapping("/{id}")
    public Object getForm(@PathVariable String id) {
        return repository.where("id", id)
                .findOne(Form.class)
                .orElseThrow(() -> new RuntimeException("未找到表单"))
                .getSchemaData();
    }

    @GetMapping("/{id}/export")
    public Form exportForm(@PathVariable String id, HttpServletResponse response) {
        var form = repository.where("id", id)
                .findOne(Form.class)
                .orElseThrow(() -> new RuntimeException("未找到表单"));

        response.setHeader("Content-Disposition", "attachment; filename=" + id + ".json");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return form;
    }

    @PostMapping("/import/{category}")
    public void importForm(@PathVariable String category, MultipartFile file) {
        try {
            var form = JsonUtils.decode(new String(file.getBytes()), Form.class);
            var categoryObj = new Category();
            categoryObj.setId(category);
            form.setCategory(categoryObj);
            this.save(form);
        } catch (IOException e) {
            throw new RuntimeException("导入表单失败", e);
        }
    }

}
